package com.ruoyi.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.Listener.FactoryListener;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.domain.Dictionary;
import com.ruoyi.domain.FactoryInfo;
import com.ruoyi.domain.SysDistrict;
import com.ruoyi.service.DictionaryService;
import com.ruoyi.service.SysDistrictService;
import com.ruoyi.utils.EasyExcelConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.service.FactoryInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import static cn.hutool.core.lang.tree.TreeUtil.build;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-02-28
 */
@RestController
@RequestMapping("/manage")
public class FactoryInfoController extends BaseController
{
    @Autowired
    FactoryInfoService factoryInfoService;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    SysDistrictService sysDistrictService;


    @PostMapping("bing")
    public List<FactoryInfo> bing(String name,String address){
        List<FactoryInfo> list =  factoryInfoService.bingtu(name,address);
        list.addAll(new ArrayList<>());
        return list;
    }

    @GetMapping("dislist")
    public R dislist(Integer parentId){
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //自定义属名 都有默认值
        treeNodeConfig.setIdKey("value");
        treeNodeConfig.setNameKey("label");
        //最大递归限度
        treeNodeConfig.setDeep(3);
        List<SysDistrict> list = sysDistrictService.listAll();
        //转换器(含义:找出父节点为字符串零的所有子节点,并递归查找对应得到子节点,深度最多为3)
        List<Tree<String>> treeNodes = TreeUtil.build(list, "-1", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getRegionId());
                    tree.setParentId(treeNode.getRegionParentId());
                    tree.setName(treeNode.getRegionName());
                });
        return R.ok(treeNodes);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FactoryInfo factoryInfo)
    {
        startPage();
        List<FactoryInfo> list = factoryInfoService.selectFactoryInfoList(factoryInfo);
        return getDataTable(list);
    }

    @GetMapping("diclist")
    public R diclist(){
        List<Dictionary> list = dictionaryService.list();
        return R.ok(list);
    }


    /**
     * 导出数据
     * */
    @PostMapping("/export")
    public void exportUserExcel(HttpServletResponse response) throws IOException {
        List<FactoryInfo> list = factoryInfoService.selectFactoryInfoListAll();
        //System.err.println(list);
        //遍历循环
        for (FactoryInfo factoryInfo : list) {
            //将状态字段替换
            if ("是".equals(factoryInfo.getStatus())){
                factoryInfo.setStatus("1");
            }else {
                factoryInfo.setStatus("2");
            }

        }
        response.setContentType(EasyExcelConfig.RESPONSE_TYPE);
        response.setCharacterEncoding(EasyExcelConfig.CHARSET);
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=factory.xls");
        EasyExcel.write(response.getOutputStream(),FactoryInfo.class).sheet("工厂管理数据").doWrite(list);

    }

    /**
     * 导入数据
     * @param file
     */
    @PostMapping("importData")
    public AjaxResult importData(MultipartFile file) throws IOException {
        List<FactoryInfo> list = EasyExcel.read(file.getInputStream())
                // 注册监听器，可以在这里校验字段
                .registerReadListener(new FactoryListener())
                .head(FactoryInfo.class)
                .sheet()
                .headRowNumber(2)
                .doReadSync();
        for (FactoryInfo factoryInfo : list) {
            System.err.println();
            factoryInfoService.insertFactoryInfo(factoryInfo);
        }

        return success("导入成功");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */

    @GetMapping(value = "/{factoryId}")
    public AjaxResult getInfo(@PathVariable("factoryId") Long factoryId)
    {
        return success(factoryInfoService.selectFactoryInfoByFactoryId(factoryId));
    }

    /**
     * 新增【请填写功能名称】
     */

    //@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FactoryInfo factoryInfo)
    {
        long nextId = IdUtil.getSnowflake().nextId();
        factoryInfo.setStatus("1");
        factoryInfo.setFactoryNum(nextId);
        return toAjax(factoryInfoService.insertFactoryInfo(factoryInfo));
    }

    /**
     * 修改【请填写功能名称】
     */

    //@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FactoryInfo factoryInfo)
    {
        return toAjax(factoryInfoService.updateFactoryInfo(factoryInfo));
    }

    /**
     * 删除【请填写功能名称】
     */

    //@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{factoryIds}")
    public AjaxResult remove(@PathVariable Long[] factoryIds)
    {
        return toAjax(factoryInfoService.deleteFactoryInfoByFactoryIds(factoryIds));
    }
}
